<?php

namespace plugin\admin\app\controller;

use app\services\RequestService;
use support\Cache;
use support\Db;
use Illuminate\Support\Facades\Schema;
use support\Request;
use support\Response;
use plugin\admin\app\model\IgnoreGood;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 屏蔽奖励商品 
 */
class IgnoreGoodController extends Crud
{
    
    /**
     * @var IgnoreGood
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new IgnoreGood;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('ignore-good/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return $this->insert1($request);
        }
        return view('ignore-good/insert');
    }

    public function insert1($request): Response
    {
        // 查询商品是否存在
        $goods = $this->model->where('barcode', $request->input('barcode'))->first();
        if (!empty($goods)){
            return $this->json(1, '商品已屏蔽');
        }
        $data = $this->insertInput($request);
        $id = $this->doInsert($data);
       IgnoreGood::updateIgnoreGoods();
        return $this->json(0, 'ok', ['id' => $id]);
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            [$id, $data] = $this->updateInput($request);
            $this->doUpdate($id, $data);
            IgnoreGood::updateIgnoreGoods();
            return $this->json(0);
        }
        return view('ignore-good/update');
    }

    protected function doDelete(array $ids)
    {
        if (!$ids) {
            return;
        }
        $primary_key = $this->model->getKeyName();
       IgnoreGood::whereIn($primary_key, $ids)->delete();
       IgnoreGood::updateIgnoreGoods();
    }

    public function synchronous()
    {
        $barcodes = IgnoreGood::whereNull('uid')->pluck('barcode')->toArray();
        if (!empty($barcodes)){
            $result =  RequestService::queryProductByBarcodes($barcodes);
        }
        // 获取数据表的所有字段名
        $columns = Db::schema()->getColumnListing('wa_ignore_goods');

        if (!empty($result['data'])){
            foreach ($result['data'] as $v){
                $dataToUpdate = array_intersect_key($v, array_flip($columns));
                IgnoreGood::where('barcode', $v['barcode'])->update($dataToUpdate);
            }
        }

        return $this->json(0, 'success');
    }
}
